package com.wumao.controller.admin;

import com.wumao.pojo.Tag;
import com.wumao.pojo.Type;
import com.wumao.service.TagService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

/**
 * @author Gaowumao
 * @Decripted
 * @Email none-j@qq.com
 * @create 2021-04-16 15:59
 */
@Controller
@RequestMapping("/admin")
public class TagController  {

    @Autowired
    private TagService tagService;

    /*分页，每页三条，通过id来排序*/
    @RequestMapping("/tags")
    /*分页，每页十条，通过id来排序。并且是降序*/
    public String types(@PageableDefault(size = 10,sort = {"id"},
            direction = Sort.Direction.DESC) Pageable pageable, Model model){
        model.addAttribute("page",  tagService.listTag(pageable)) ;

        return "admin/tags";
    }


    @RequestMapping("/tags/input")
    public String input(){
        return "admin/tags-input";
    }

    @RequestMapping("/tags/{id}/input")
    public String editInput(@PathVariable Long id, Model model){
        model.addAttribute("tag",tagService.getTag(id));
        return "admin/tags-input";
    }

    @RequestMapping("/editAdd")
    public String editAdd(Tag tag, RedirectAttributes attributes){

        Tag t = tagService.addTag(tag);
        if (t == null){
            attributes.addFlashAttribute("message","操作失败");
        }else{
            attributes.addFlashAttribute("message","操作成功");
        }
        return "redirect:/admin/tags";
    }
    @RequestMapping("/editAdd/{id}")
    public String update(Tag tag, @PathVariable Long id , RedirectAttributes attributes){

//        Type type1 = typeService.getTypeByname(type.getName());
//        if (type1 != null){
//            result.rejectValue("name","nameError","分类不能重复添加");
//        }

        Tag t = tagService.updateTag(id,tag);
        if (t == null){
            attributes.addFlashAttribute("message","更新失败");
        }else{
            attributes.addFlashAttribute("message","更新成功");
        }
        return "redirect:/admin/tags";
    }

    @RequestMapping("/tags/{id}/delete")
    public String delete(@PathVariable Long id,RedirectAttributes attributes){
        tagService.deleteTag(id);
        attributes.addFlashAttribute("message","删除成功");
        return "redirect:/admin/tags";
    }

}
